//
//  HotSearchKeyHandler.m
//  CToolBox
//
//  Created by crj on 16/9/19.
//  Copyright © 2016年 oyf. All rights reserved.
//

#import "HotSearchKeyHandler.h"
//keywords ,time
static HotSearchKeyHandler *shareInstance = nil;

NSString *const kHotSearchKeyTableName = @"hotSearchKey";

@interface HotSearchKeyHandler(){
    NSString *_DBPath;
}

@end

@implementation HotSearchKeyHandler

#pragma mark - 保存或更新

- (void)saveOrUpdateWithSearchKey:(NSString *)searchKey date:(NSDate *)date{
    
    //检测是否存在，更新数据库数据
    NSString * check=[NSString stringWithFormat:@"SELECT * FROM %@ WHERE keywords ='%@'",kHotSearchKeyTableName,searchKey];
    
    // 更新数据库
    FMResultSet * resultSet = [_db executeQuery:check];
    
    if (![resultSet next]) {
        //保存
        [self saveWithSearchKey:searchKey date:date];
    }
    else{
        //更新
        [self updateWithSearchKey:searchKey date:date];
    }

}

//更新
-(void)updateWithSearchKey:(NSString *)searchKey date:(NSDate *)date{
    //keywords ,time

    [_db executeUpdateWithFormat:@"UPDATE hotSearchKey SET time=%@ WHERE keywords=%@",date,searchKey];
    
}

//保存
-(void)saveWithSearchKey:(NSString *)searchKey date:(NSDate *)date{

    [_db executeUpdateWithFormat:@"INSERT INTO hotSearchKey (keywords , time) VALUES (%@, %@)",searchKey, date];
}

#pragma mark - 查询

-(NSArray *)selectList{
    
    NSString * query = [NSString stringWithFormat:@"SELECT * FROM %@ ORDER BY time DESC",kHotSearchKeyTableName];
    
    FMResultSet * resultSet = [_db executeQuery:query];

    NSMutableArray *array = [[NSMutableArray alloc] init];
    while ([resultSet next]) {
        
        NSString *keywords = [resultSet stringForColumn:@"keywords"];
        [array addObject:keywords];
    }
    
    [resultSet close];
    return array;
    
}

#pragma mark - 清空表

- (BOOL)clearHistory{
    
    __block BOOL result = NO;
    NSString *sql = [NSString stringWithFormat:@"DELETE FROM %@",kHotSearchKeyTableName];
    result = [_db executeUpdate:sql];
    NSLog(result?@"清空成功":@"清空失败");
    return result;
    
}



#pragma mark - 初始化

+ (HotSearchKeyHandler *)shareInstanceMethod{
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        shareInstance = [[HotSearchKeyHandler alloc] init];
    });
    return shareInstance;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self initializeDBWithName:kDataBaseName];

    }
    return self;
}

#pragma mark - 打开数据库 ---
- (void) initializeDBWithName : (NSString *) name {
    
    if (!name) {
        NSLog(@"数据库名称不能为空");
        return ;
    }
    
    // 沙盒Docu目录
    NSString *docp = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,NSUserDomainMask, YES) objectAtIndex:0];
    _DBPath = [docp stringByAppendingString:[NSString stringWithFormat:@"/%@",name]];
    NSLog(@"数据库地址：%@",_DBPath);
    [self connect];
}

// 连接数据库 或 创建（不存在的话）
- (void) connect {
    if (!_db) {
        _db = [[FMDatabase alloc] initWithPath:_DBPath];
    }
    if (![_db open]) {
        NSLog(@"不能打开数据库 或 不存在该数据库");
    }else{
        [self createDataBase];
    }
}
//创建数据表
- (void)createDataBase{
    
    FMResultSet * resultSet = [_db executeQuery:[NSString stringWithFormat:@"select count(*) from sqlite_master where type ='table' and name = '%@'",kHotSearchKeyTableName]];
    
    [resultSet next];
    
    NSInteger count = [resultSet intForColumnIndex:0];
    
    
    BOOL existTable = count > 0;
    
    if (existTable) {
        // TODO:是否更新数据库
        NSLog(@"%@_数据库已经存在",kHotSearchKeyTableName);
        
    } else {
        // TODO: 插入新的数据表
        NSString *sql=[NSString stringWithFormat:@"create table if not exists %@(keywords ,time)",kHotSearchKeyTableName];
        
        BOOL result = [_db executeUpdate:sql];
        if (!result) {
            NSLog(@"%@_数据库创建失败",kHotSearchKeyTableName);
            
        } else {
            
        }
    }
}



@end
